import "package:share_image_server/export_all.dart";

//文件不能被读取时初始化配置文件
Future<ConfigModel> _createFile(File file) async {
  String configJson = '''
{
  "host": "0.0.0.0",
  "port": 8081,
  "check_token": "kpb_token",
  "log_path": "/kpb.log",
  "save_path": "/static/",
  "console_log": false,
  "info_m":true
}''';
  try {
    file.createSync(recursive: true);
    final writeJson = file.openWrite(mode: FileMode.write);
    writeJson.write(configJson);
    await writeJson.flush();
    await writeJson.close();
    final jsonString = await file.readAsString();
    return configModelFromJson(jsonString.toString());
  } on FileSystemException catch (e) {
    logE(e.toString());
    return configModelFromJson(configJson);
  }
}

//读取配置文件
Future<ConfigModel> readConfigFromFile(String filePath) async {
  final file = File(filePath);
  if (!await file.exists()) {
    return _createFile(file);
  }
  final jsonString = await file.readAsString();
  try {
    var json = jsonDecode(jsonString);
    return ConfigModel.fromJson(json);
  } catch (e) {
    return _createFile(file);
  }
}
